package ug.co.icom.kyazze.healthticket.email;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import ug.co.icom.kyazze.healthticket.data.AppData;
import ug.co.icom.kyazze.healthticket.data.EmailReturnValue;
import ug.co.icom.kyazze.healthticket.data.User;
import ug.co.icom.kyazze.healthticket.mongoHQ.MongoHQAppData;
import ug.co.icom.kyazze.healthticket.mongoHQ.MongoHQEmailSearch;

public class MailService extends AsyncTask<String, Void, EmailReturnValue> {

	User loggedIn;
	private Context context;
	
	public MailService(Context context)
	{
		this.context = context;
	}
	public EmailReturnValue sendEmail(String to) throws AddressException, MessagingException, InterruptedException, ExecutionException
	{
		EmailReturnValue erv;
		String host = "smtp.gmail.com";

        loggedIn = new User();
		MongoHQEmailSearch userdata = new MongoHQEmailSearch();
		loggedIn = userdata.getUserDetailsFromEmail(to);
		
		if(loggedIn != null)
		{
			if(!loggedIn.PhoneNumber.equals(""))
			{
				AppData appdata = new AppData();
				MongoHQAppData app = new MongoHQAppData();
				appdata = app.getAppData();

				if(appdata != null)
				{
					if((!appdata.Email.equals("")) && (!appdata.Password.equals("")))
					{
						emailFunction(host, appdata.Email, appdata.Password, to);
						erv = new EmailReturnValue();
						erv.retVal = true;
						erv.Message = "";
					}
					else
					{
						erv = new EmailReturnValue();
						erv.retVal = false;
						erv.Message = "Invalid application details";
					}
				}
				else
				{
					erv = new EmailReturnValue();
					erv.retVal = false;
					erv.Message = "No application details";
				}
			}
			else
			{
				erv = new EmailReturnValue();
				erv.retVal = false;
				erv.Message = "Invalid User details";
			}
		}
		else
		{
			erv = new EmailReturnValue();
			erv.retVal = false;
			erv.Message = "That email is not registered!";
		}
		
		return erv;                
    }
	
	private void emailFunction(String host, String address, String pass, String to)
	{
		try
		{
		Multipart multiPart;
        String finalString="";
         
 
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", address);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, null);
        DataHandler handler=new DataHandler(new ByteArrayDataSource(finalString.getBytes(),"text/plain" ));
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(address));
        message.setDataHandler(handler);
         
        multiPart=new MimeMultipart();
 
        InternetAddress toAddress;
        toAddress = new InternetAddress(to);
        message.addRecipient(Message.RecipientType.TO, toAddress);
        message.setSubject("Password Recovery From Health Ticket");
        message.setContent(multiPart);
        message.setText("Your login Details are\n\tUser Name:\t"+
        loggedIn.PhoneNumber+"\n\tPassword:\t"+loggedIn.PassCode);
         
        Transport transport = session.getTransport("smtp");
        transport.connect(host,address , pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
		}
		catch(Exception e)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setMessage(e.getMessage());
			builder.setCancelable(true);
			AlertDialog alert = builder.create();
			alert.show();
		}
	}

	@Override
	protected EmailReturnValue doInBackground(String... params) {
		
		try
		{
			String email = params[0];			
			return sendEmail(email);
		}
		catch(Exception e)
		{
			EmailReturnValue erv = new EmailReturnValue();
			erv.retVal = false;
			erv.Message = "An error occurred";
			return erv;
		}
	}

}
